<?php

namespace app\api\controller\product;


use app\api\controller\Api;
use app\common\product\model\Product;
use app\common\product\model\ProductAttr;
use app\common\product\model\ProductAttrResult;
use app\common\product\model\ProductAttrValue;
use app\common\product\model\ProductCategory;
use app\common\product\model\ProductDescription;
use app\common\product\model\ProductRuleValue;
use app\common\product\validate\ProductValidate;
use app\common\system\logic\FormLogic;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use util\Format;

class Goods extends Api
{
    public function index()
    {
        $post = $this->request->post();

        $where = [];
        // 获取field
        if (isset($post['keyword']) && !empty($post['keyword'])) $where[] = ['title', 'like', "%{$post['keyword']}%"];

        $model = new Product();
        list($cfg) = Format::pagination($post);
        if (isset($post['cate_id']) && !empty($post['cate_id'])) {
            $model = $model->whereRaw('FIND_IN_SET(?, cate_id)', [$post['cate_id']]);
        }
        $pg = $model->where($where)->order('sort desc,id')->paginate($cfg);
        $rows = $pg->getCollection();
        foreach ($rows as $row) {
            $row->append(['category']);
        }

        // 返回接口数据
        $result['list'] = $rows;
        $result['pagination'] = Format::pgResult($pg);

        return success($result, '获取数据成功');
    }

    public function getGoodsByCategory()
    {
        $post = $this->request->post();
        if (empty($post['cate_id'])) return error([], '参数错误');

        $model = new Product();
        $list = $model->whereRaw('FIND_IN_SET(?, cate_id)', [$post['cate_id']])->order('sort desc,id')->select();
        foreach ($list as $row) {
            $row->append(['spec']);
        }
        $result['list'] = $list;

        return success($result);
    }

    public function read()
    {
        $post = $this->request->post();
        if (empty($post['id'])) return error([], '参数错误');

        $model = new Product();
        $result['product'] = $model->where('id', $post['id'])->find();

        $cateModel = new ProductCategory();
        $cateIds = $cateModel->where('product_id', $post['id'])->column('cate_id');
        $result['product']['cate_id'] = $cateIds;

        // 获取商品属性result
        $attrResultModel = new ProductAttrResult();
        $attrResult = $attrResultModel->where('product_id', $post['id'])->find();
        $result['attr_result'] = json_decode($attrResult['result'], true);

        // 获取商品详情
        $descriptionModel = new ProductDescription();
        $desc = $descriptionModel->where('product_id', $post['id'])->find();
        $result['description'] = $desc;

        return success($result);
    }

    public function create(): \think\response\Json
    {
        $post = $this->request->post();
        // 创建的时候清除干扰的信息
        unset($post['id']);
        // 验证提交
        $validate = new ProductValidate();
        if (!$validate->scene('create')->check($post['product'])) return error([], $validate->getError());
        $now = time();

        $model = new Product();
        // 开启事务
        $model->startTrans();
        $user = $this->request->user;
        $post['operator_id'] = $user['id'];
        try {
            if ($post['product']['spec_type'] == 0) {
                $post['product'] = array_merge($post['product'], $post['spec']);
            }
            $post['product']['add_time'] = $now;
            $model->save($post['product']);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        $productId = $model->id;
        // 创建商品类别
        // $post['cate_id']
        $cateData = [];
        foreach ($post['product']['cate_id'] as $row) {
            $cate = [];
            $cate['product_id'] = $productId;
            $cate['cate_id'] = $row;
            // $data['add_time'] = $now;
            $cateData[] = $cate;
        }
        try {
            $cateModel = new ProductCategory();
            $cateModel->saveAll($cateData);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        if ($post['product']['spec_type'] == 0) {
            $spec = $post['spec'];
            $spec['detail'] = ['默认'];
            $post['attr'][] = $spec;
        }

        // 生成商品的详情
        $productDescription = new ProductDescription();
        $descriptionData = [
            'product_id' => $productId,
            'description' => $post['desc']['description'],
            'type' => 1
        ];
        try {
            $productDescription->save($descriptionData);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        $attrs = [];
        $attrIds = [];
        $attrPids = [];
        $attrValues = [];
        foreach ($post['attr'] as $row) {
            // 构造attr
            foreach ($row['detail'] as $key => $val) {
                if (!isset($attrs[$key])) {
                    $attrs[$key] = [];
                }

                if (!in_array($val, $attrs[$key])) {
                    $attrs[$key][] = $val;
                }
            }

            // 构造product_attr_value,product_id,suk
            $row['product_id'] = $productId;
            $row['suk'] = implode('|', $row['detail']);
            $row['suk_ids'] = implode('|', $row['suk_ids']);
            // 8位唯一码
            $row['unique'] = md5($productId . $row['suk']);
            $attrValues[] = $row;
        }

        // 生成 product_attr表所需要的数据
        $attrData = [];
        $productAttr = new ProductAttr();
        $attrRes['attr'] = [];
        foreach ($attrs as $key => $val) {
            $attr = [];
            $attr['product_id'] = $productId;
            $attr['attr_name'] = $key;
            $attr['attr_values'] = implode(',', $val);
            $attrData[] = $attr;
            // 生成product_attr_result需要的数据结构
            $attrRes['attr'][] = [
                'value' => $key,
                'detail' => $val
            ];
        }

        try {
            $productAttr->saveAll($attrData);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        // 生成 product_attr_value
        $productAttrValue = new ProductAttrValue();
        try {
            $productAttrValue->saveAll($attrValues);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        // 生成product_attr_result
        $productAttrResult = new ProductAttrResult();
        $attrRes['value'] = $post['attr'];
        try {
            $attrResData = [
                'product_id' => $productId,
                'result' => json_encode($attrRes)
            ];
            $productAttrResult->save($attrResData);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        $model->commit();
        return success([], '添加商品分类成功');
    }

    public function update(): \think\response\Json
    {
        $post = $this->request->post();

        // 验证提交
        $validate = new ProductValidate();
        if (!$validate->scene('edit')->check($post)) return error([], $validate->getError());
        $post['id'] = $post['product']['id'];

        $model = new Product();
        $product = $model->where('id', $post['id'])->find();
        if (empty($product)) return error([], '商品已不存在');

        $now = time();
        $model = new Product();
        // 开启事务
        $model->startTrans();
        $user = $this->request->user;
        $post['operator_id'] = $user['id'];

        // 更新商品基本信息
        try {
            if ($post['product']['spec_type'] == 0) {
                $post['product'] = array_merge($post['product'], $post['spec']);
            }
            $post['product']['update_time'] = $now;

            $product->save($post['product']);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        // 更新商品类别
        $cateModel = new ProductCategory();
        $cateModel->where('product_id', $post['id'])->delete();
        $cateData = [];
        foreach ($post['product']['cate_id'] as $row) {
            $cate = [];
            $cate['product_id'] = $post['id'];
            $cate['cate_id'] = $row;
            $data['add_time'] = $now;
            $cateData[] = $cate;
        }
        try {
            $cateModel->saveAll($cateData);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        if ($post['product']['spec_type'] == 0) {
            $spec = $post['spec'];
            $spec['detail'] = ['默认'];
            $post['attr'][] = $spec;
        }

        // 更新商品的详情
        $productDescription = new ProductDescription();
        $descriptionData = [
            'product_id' => $post['id'],
            'description' => json_encode($post['desc']['description']),
            'type' => 1
        ];
        try {
            $productDescription->where('product_id', $post['id'])->update($descriptionData);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        $attrs = [];
        $attrValues = [];
        foreach ($post['attr'] as $row) {
            // 构造attr
            $names = $row['detail'];
            foreach ($names as $key => $val) {
                if (!isset($attrs[$key])) $attrs[$key] = [];
                if (!in_array($val, $attrs[$key])) $attrs[$key][] = $val;
            }

            // 构造product_attr_value,product_id,suk
            $row['product_id'] = $post['id'];
            $row['suk'] = implode('|', $row['detail']);
            // 8位唯一码
            $row['unique'] = md5($post['id'] . $row['suk']);
            $attrValues[] = $row;
        }
        // 生成product_attr
        $attrData = [];
        $productAttr = new ProductAttr();
        $attrRes['attr'] = [];
        foreach ($attrs as $key => $val) {
            $attr = [];
            $attr['product_id'] = $post['id'];
            $attr['attr_name'] = $key;
            $attr['attr_values'] = implode(',', $val);
            $attrData[] = $attr;
            // 生成product_attr_result
            $attrRes['attr'][] = [
                'value' => $key,
                'detail' => $val
            ];
        }
        try {
            $productAttr->where('product_id', $post['id'])->delete();
            $productAttr->saveAll($attrData);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        // 生成product_attr_value
        $productAttrValue = new ProductAttrValue();
        try {
            $productAttrValue->where('product_id', $post['id'])->delete();
            foreach ($attrValues as &$row) {
                $row['suk_ids'] = implode('|', $row['suk_ids']);
                $row['detail'] = implode('|', $row['detail']);
            }
            $productAttrValue->saveAll($attrValues);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        // 生成product_attr_result
        $productAttrResult = new ProductAttrResult();
        $attrRes['value'] = $post['attr'];
        try {
            $attrResData = [
                'product_id' => $post['id'],
                'result' => json_encode($attrRes)
            ];
            $productAttrResult->where('product_id', $post['id'])->update($attrResData);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        $model->commit();
        return success([], '更新成功');
    }

    // 切换商品显示状态
    public function switchShow()
    {
        $post = $this->request->post();
        if (empty($post['id'])) return error([], '参数错误');

        $model = new Product();
        $row = $model->where('id', $post['id'])->find();
        if (empty($row)) return error([], '商品已不存在');
        $rs = $row->save(['is_show' => $post['is_show']]);

        if ($rs) {
            return success([], '切换成功');
        } else {
            return error([], '切换失败');
        }
    }

    // 切换商品赠送状态
    public function switchGift()
    {
        $post = $this->request->post();
        if (empty($post['id'])) return error([], '参数错误');

        $model = new Product();
        $row = $model->where('id', $post['id'])->find();
        if (empty($row)) return error([], '商品已不存在');
        $rs = $row->save(['is_present' => $post['is_present']]);

        if ($rs) {
            return success([], '切换成功');
        } else {
            return error([], '切换失败');
        }
    }


    public function delete()
    {
        $post = $this->request->post();
        // 验证提交
        $validate = new ProductValidate();
        if (!$validate->scene('delete')->check($post)) return error([], $validate->getError());

        $model = new Product();
        $row = $model->where('id', $post['id'])->find();
        if (empty($row)) return error([], '商品分类已不存在');
        $rs = $row->delete();

        if ($rs) {
            return success([], '删除成功');
        } else {
            return error([], '删除失败');
        }
    }
}
